package com.xpc.dateapi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xpc.dateapi.service.IDateApiService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Classname DateApiIml
 * @Created by xpc
 * @Date 2021/10/18 16:49
 * @version: 1.0
 */
@Service
public class DateApiIml implements IDateApiService {

    private static final Logger log = LoggerFactory.getLogger(DateApiIml.class);

    // json 文件路径
    private static final String JSON_PATH = "templates/@date_data.json";

    // 替换的关键字
    private static final String KEYWORD = "@date";


    /**
     * 单个日期的查询
     *
     * @param: date
     * @return: 0, 1, 2
     * @createAuthor: xpc
     * @createDate: 2021-10-18 16:57
     * @version: 1.0
     */
    @Override
    public String singleDate(String date) {
        String stats = "";
        if (StringUtils.isEmpty(date)) {
            return stats;
        }
        // 截取年份
        String year = date.substring(0, 4);
        String time = date.substring(4);
        // 字符串替换，把json文件名替换成对应的年份
        String jsonPath = DateApiIml.JSON_PATH.replace(DateApiIml.KEYWORD, year);
        String reader = DateApiIml.reader(jsonPath);
        if (StringUtils.isEmpty(reader)) {
            return "系统未录入该年份的数据";
        }
        Map<String, Integer> map = JSONObject.parseObject(reader, Map.class);
        if (map.containsKey(time)) {
            stats = String.valueOf(map.get(time));
        } else {
            stats = this.isWeekend(date);
        }
        return stats;
    }

    /**
     * 多个日期的查询
     *
     * @param: dates
     * @return: {data:0,1,2}
     * @createAuthor: xpc
     * @createDate: 2021-10-18 16:57
     * @version: 1.0
     */
    @Override
    public String moreDate(String[] dates) {
        Map<String, String> map = new IdentityHashMap();
        for (int i = 0; i < dates.length; i++) {
            String date = dates[i];
            String s = this.singleDate(date);
            if (StringUtils.isNotEmpty(s)) {
                map.put(date, s);
            }
        }
        return JSONObject.toJSONString(map);
    }

    /**
     * 读取json文件
     *
     * @param: filePath
     * @return: 文件内容
     * @createAuthor: xpc
     * @createDate: 2021-10-18 17:14
     * @version: 1.0
     */
    private static String reader(String filePath) {
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            InputStream inputStream = classPathResource.getInputStream();
            if (null != inputStream) {
                /** 字节流读取json文件 */
                InputStreamReader read = new InputStreamReader(inputStream, "UTF-8");
                StringBuffer sb = new StringBuffer();
                int ch = 0;
                while ((ch = read.read()) != -1) {
                    sb.append((char) ch);
                }
                read.close();
                String ret = sb.toString();
                if (StringUtils.isNotEmpty(ret)) {
                    return ret;
                }
            }
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            log.error("Cannot find the file specified!");
            e.printStackTrace();
        } catch (IOException e) {
            log.error("Error reading file content!");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param: date
     * @return: 0:工作日  1:周末
     * @createAuthor: xpc
     * @createDate: 2021-10-19 10:04
     * @version: 1.0
     */
    private String isWeekend(String date) {
        String stats = "";
        try {
            Calendar calendar = new GregorianCalendar();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date parse = sdf.parse(date);
            calendar.setTime(parse);
            int i = calendar.get(Calendar.DAY_OF_WEEK);
            // 1为周日  7为周日
            if (i == 1 || i == 7) {
                stats = "1";
            } else {
                stats = "0";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return "请输入正确的日期格式格";
        }
        return stats;
    }
}
